package com.app.car.check;

import android.Manifest;

import com.app.car.basis.BasisActivity;
import com.app.car.basis.BasisApp;
import com.app.car.basis.Constants;
import com.app.car.bean.RfidListBean;
import com.app.car.dialog.CheckFinishDialog;
import com.app.car.greendao.GreenDaoUtils;
import com.app.car.util.ExcelUtil;
import com.mylhyl.acp.Acp;
import com.mylhyl.acp.AcpListener;
import com.mylhyl.acp.AcpOptions;

import java.io.File;
import java.util.List;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.ObservableEmitter;
import io.reactivex.rxjava3.core.ObservableOnSubscribe;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.schedulers.Schedulers;
import my.DialogUtils;
import my.LogUtil;

public class CheckPresentImpl implements CheckPresent{

    BasisActivity activity;
    CheckView checkView;

    public CheckPresentImpl(BasisActivity activity,CheckView checkView){
        this.checkView = checkView;
        this.activity = activity;
    }

    @Override
    public void toSave(RfidListBean rfidListBean) {
//        rfidListBean.setTime(System.currentTimeMillis());
        GreenDaoUtils.rfidBeanInsertData(rfidListBean, new GreenDaoUtils.GreenDaoInserCallBack() {
            @Override
            public void onDataInsert(int count) {
                switch (count){
                    case 1:
                        BasisApp.showToast("保存成功");
                        break;
                    default:
                        BasisApp.showToast("保存失败");
                        break;
                }
            }
        });
    }

    @Override
    public void toCheck(RfidListBean rfidListBean) {
        activity.showLoading("对比中...请稍等!");

        Observable.create(new ObservableOnSubscribe<RfidListBean>() {
            // 1\. 创建被观察者 & 生产事件
            @Override
            public void subscribe(ObservableEmitter<RfidListBean> emitter) throws Exception {
                rfidListBean.toCheck();
                emitter.onNext(rfidListBean);
                emitter.onComplete();
            }
        })   .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<RfidListBean>() {
            // 2\. 通过通过订阅（subscribe）连接观察者和被观察者
            // 3\. 创建观察者 & 定义响应事件的行为
            @Override
            public void onSubscribe(Disposable d) {

            }
            // 默认最先调用复写的 onSubscribe（）

            @Override
            public void onNext(RfidListBean rfidListBean) {
                activity.dismissProgress();
                CheckFinishDialog dialog = new CheckFinishDialog(activity,rfidListBean);
                dialog.show();
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
    }


    @Override
    public void exportExcel(RfidListBean rfidListBean) {
        activity.showLoading("导出中");
        File file = new File(Constants.DIR_EXCEL);
        if (!file.exists()) {
            file.mkdirs();
        }
        Acp.getInstance(activity).request(new AcpOptions.Builder()
                        .setPermissions(
                                Manifest.permission.WRITE_EXTERNAL_STORAGE
                                , Manifest.permission.READ_EXTERNAL_STORAGE

                        ).build(),
                new AcpListener() {
                    @Override
                    public void onGranted() {
                        DialogUtils.showEditTextDialog(activity, "提示", "请输入文件名称", "确定", new DialogUtils.TextResult() {
                            @Override
                            public void resultText(String text) {
                              toExport(text,rfidListBean);
                            }
                        });
                    }

                    @Override
                    public void onDenied(List<String> permissions) {
                        BasisApp.showToast(permissions.toString() + "权限拒绝");

                    }
                });
    }

    private void toExport(String text,RfidListBean rfidListBean){
        new Thread(new Runnable() {
            @Override
            public void run() {
//                TimeUtils.getTimeLongToStrByFormat(rfidListBean.getTime(), "yyyy-MM-dd");
//                String[] title = {"仓库","账面数","货品名称","已盘数","盘盈","盘亏","年份","月份"};
                String[] title = {"仓库","箱码","货品类别","货品编码","名称","规格","已盘数","盘盈","盘亏","年份","月份"};
                String filePath = Constants.DIR_EXCEL+text+".xls";//文件的路径
                ExcelUtil.initExcel(filePath, text, title);
                LogUtil.d("导出initExcel（）");
                ExcelUtil.writeObjListToExcel(rfidListBean, filePath, activity);
                LogUtil.d("writeObjListToExcel（）");
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        activity.dismissProgress();
                        DialogUtils.showSuccessrDialog(activity,"提示","保存成功，转到USB界面查看");
                    }
                });

            }
        }).start();
    }

}
